package com.tedu;

import java.util.Scanner;

public class BinarySearch {
    public static void main(String[] args) {

        int [] ary = {23,45,78,88,97,98,123};
        System.out.println("输入要查找的整数：");
        int target = new Scanner(System.in).nextInt();
      int index =  binarySearch(ary,target);
      if (index!=-1){
          System.out.println("元素"+target+"的下标是："+index);
      }else {
          System.out.println("元素"+target+"不在数组里");
      }

    }

    private static int binarySearch(int[] ary, int target) {
        int start = 0, end = ary.length - 1, middle;
        while (end >= start) {
//            找到中间下标
            middle = start + ((end - start) >> 1);
//            对比middle位置的元素与target元素的大小
            if (target == ary[middle]) {
                return middle;
            } else if (target < ary[middle]) {
                //向左边缩小范围
                end = middle - 1;
            } else {
//                向右边缩小范围
                start = middle + 1;
            }
        }
            return -1;
    }
}
